package com.hspedu.hspliving.commodity.exception;

import com.hspedu.common.exception.CodeEnum;
import com.hspedu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Slf4j
@ResponseBody
@ControllerAdvice(basePackages = "com.hspedu.hspliving.commodity.controller")
public class DyControllerAdvice {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R exception(MethodArgumentNotValidException e) {
        log.error("错误："+e.getMessage());

        BindingResult result = e.getBindingResult();
        HashMap<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach(error -> map.put(error.getField(), error.getDefaultMessage()));
        return R.error(CodeEnum.INVALID_EXCEPTION.getCode(), CodeEnum.INVALID_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler({Throwable.class})
    public R handlerException(MethodArgumentNotValidException e) {
        log.error("错误："+e.getMessage());
        return R.error(CodeEnum.UNKNOWN_EXCEPTION.getCode(), CodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

}
